//
//  HPersonalDataVC.m
//  BXlive
//
//  Created by huangzhiwen on 2017/3/21.
//  Copyright © 2017年 cat. All rights reserved.
//

#import "HPersonalDataVC.h"
#import "HHPersonDataCell.h"
#import "HNickNameVC.h"                    //昵称
#import "HPersonalizedSignatureVC.h"       //个性签名
#import "NSDate+Kit.h"
#import "FilePathHelper.h"
#import <QiniuSDK.h>
#import <HXPhotoPicker.h>
#import <PGDatePickManager.h>
#import "BXPersonDataIdCell.h"
#import "BXPhotoModel.h"
#import "SLPersonButton.h"
#import "BXPersonDataPicCell.h"
#import "SLSettingGenderView.h"
#import "SLSettingBirthdayView.h"
#import "SLSettingWeightView.h"
#import "SLSettingHeightView.h"
#import "BXPhotoVC.h"
#import "BXPersonDataVoiceVC.h"
#import "BXPersonDataTagTypeVC.h"
#import <SLDeveloperTools/SLDeveloperTools.h>
#import <FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h>
#import <Masonry/Masonry.h>
#import <YYCategories/YYCategories.h>

//#import "TUILogin.h"
//#import "TUIDefine.h"
//#import <UIKit/UIKit.h>
#import "V2TIMManager.h"

@interface HPersonalDataVC ()<UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource,HXCustomNavigationControllerDelegate,HXCustomCameraViewControllerDelegate, PGDatePickerDelegate>
/** 表单视图 */

@property(nonatomic,strong)UIView *navigationView;

@property (nonatomic,strong) UITableView *mainTableView;

/** 顶部背景图 */
@property (nonatomic,strong) UIView *topSuperView;
@property (nonatomic,strong)UILabel *countLabel;
@property (nonatomic,strong)UIButton *sureBtn;
/** 顶部背景图 */
@property (nonatomic,strong) UIView *topView;
/** 顶部背景图更换按钮 */
@property (nonatomic,strong) UIButton *replaceBtn;

/** 头像 */
@property (nonatomic,strong) SLPersonButton *avatarBtn;
/** 设置头像 */
@property (nonatomic,strong) UIButton *setHeadBtn;
/** 选择器 */
@property (nonatomic,strong)UIPickerView *pickerView;

/** 省索引 */
@property (nonatomic , assign)NSInteger seletedProvinceIndex;
/** 市索引 */
@property (nonatomic , assign)NSInteger seletedCityIndex;
/** 区索引 */
@property (nonatomic , assign)NSInteger seletedAreaIndex;

@property (nonatomic , strong) NSArray *provinceArray;                  //省份的数组
@property (strong, nonatomic) NSArray *titles;
@property (strong, nonatomic) NSMutableArray *contents;

@property (nonatomic , strong) NSString * photoType;//0上传头像, 1替换背景墙照片

@property (nonatomic, strong)NSMutableArray *photoAlbums;

@property (strong, nonatomic) HXPhotoManager *manager;
//@property (strong, nonatomic) HXDatePhotoToolManager *toolManager;

@property (nonatomic, assign)NSInteger replaceIndex;

@property (nonatomic, assign)NSInteger updatePhotoSuccessCount;

@property (nonatomic, assign)NSInteger updatePhotoFailCount;

@end


@implementation HPersonalDataVC

//- (HXDatePhotoToolManager *)toolManager {
//    if (!_toolManager) {
//        _toolManager = [[HXDatePhotoToolManager alloc] init];
//    }
//    return _toolManager;
//}

- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto];
        _manager.configuration.openCamera = NO;
        _manager.configuration.saveSystemAblum = NO;
        _manager.configuration.lookGifPhoto = NO;
        _manager.configuration.selectTogether = NO;
        _manager.configuration.singleSelected = YES;
        _manager.configuration.singleJumpEdit = YES;
        _manager.configuration.movableCropBox = YES;
        _manager.configuration.movableCropBoxEditSize = NO;
        _manager.configuration.movableCropBoxCustomRatio = CGPointMake(500, 500);
        _manager.configuration.photoCanEdit = NO;
        _manager.configuration.videoCanEdit = NO;
        _manager.configuration.rowCount = 4;
        _manager.configuration.themeColor = sl_normalColors;
        _manager.configuration.openCamera = YES;
    }
    return _manager;
}


- (void)getProvince {
    [[NewHttpRequestHuang sharedNewHttpRequestHuang] CommonGetRegionTreeWithSuccess:^(id responseObject) {
        if ([responseObject[@"code"]intValue] == 0) {
            self.provinceArray = [responseObject objectForKey:@"data"];
        } else{
            [BGProgressHUD showInfoWithMessage:responseObject[@"msg"]];
        }
    } Failure:^(NSError *error) {
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    _provinceArray = [NSMutableArray array];
    _photoAlbums = [NSMutableArray new];
    NSArray *titles0 = @[NSLocalizedString(@"昵称", nil),[BXAppInfo appInfo].app_account_name,NSLocalizedString(@"性别", nil),NSLocalizedString(@"生日", nil),NSLocalizedString(@"家乡", nil),NSLocalizedString(@"身高", nil),NSLocalizedString(@"体重", nil)];
//    NSArray *titles1 = @[NSLocalizedString(@"个性签名", nil),NSLocalizedString(@"同类标签", nil),NSLocalizedString(@"语音标签", nil)];
        NSArray *titles1 = @[NSLocalizedString(@"个性签名", nil)];
    NSArray *titles2 = @[NSLocalizedString(@"背景墙", nil)];
//    _titles = @[titles0,titles1,titles2];
    _titles = @[titles0,titles1];
    self.fd_prefersNavigationBarHidden = YES;
    [self setupNavigationView];
    self.view.backgroundColor = sl_BGColors;
    [self createTableView];
    
    [self getProvince];
    
    if (!_type && !_liveUser) {
        _liveUser = [BXLiveUser currentBXLiveUser];
    }
    
    [self didGetBXLiveUser:_liveUser];
    
    [self getPhotoAlbum];
}

-(void)getPhotoAlbum{
//    获取照片墙照片
    BXLiveUser *user = [BXLiveUser currentBXLiveUser];
    [self.photoAlbums removeAllObjects];
//    [self.photoAlbums addObjectsFromArray:user.photo_wall_image];
    if (user.photo_wall_image && user.photo_wall_image.count > 0) {
        for (int i=0; i<user.photo_wall_image.count; i++) {
            HPersonalPhotoModel *model = [[HPersonalPhotoModel alloc] init];
            model.url = user.photo_wall_image[i];
            model.image = nil;
            model.index = i;
            [self.photoAlbums addObject:model];
        }
    }
    [self updateTopView];
}
#pragma mark - 更新照片墙
-(void)updateTopView{
//    先确认高度
    NSInteger allCount = self.photoAlbums.count + 1;
//    行数 （要加上 `添加图片的按钮`）
    
    NSInteger cellCount = (int)(self.photoAlbums.count / 3) + 1;
    if (allCount<8) {
        cellCount = (int)((self.photoAlbums.count+1) / 3) + 1;
    }
    
    CGRect topVR = self.topView.frame;
    
    topVR.size.height = cellCount * (__ScaleWidth(122)) + __ScaleWidth(15);
    
    self.topView.frame = topVR;
    
    CGRect tsVR = self.topSuperView.frame;
    
    tsVR.size.height = cellCount * (__ScaleWidth(122)) + __ScaleWidth(15 + 45);
    self.topSuperView.frame = tsVR;
    
    [self.topView removeAllSubViews];
//    开始布局
    for (int k=0; k<allCount; k++) {
        SLPersonButton *btn = [SLPersonButton buttonWithType:UIButtonTypeCustom];
        CGFloat x = __ScaleWidth(12 + (106+15)*(k%3));
        CGFloat y = __ScaleWidth(15) + __ScaleWidth((15+107)*(k/3));
        btn.frame = CGRectMake(x, y, __ScaleWidth(106), __ScaleWidth(107));
        [self.topView addSubview:btn];
        
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = 12;
        
        btn.backgroundColor = sl_subBGColors;
        
        btn.imageView.contentMode = UIViewContentModeScaleAspectFill;
        
//        默认第一个位头像
        if (k == 0) {
            [btn yy_setImageWithURL:[NSURL URLWithString:_liveUser.avatar] forState:BtnNormal placeholder:CImage(@"placeholder_avatar_67")];
            [btn addTarget:self action:@selector(setHeadBtnClick) forControlEvents:BtnTouchUpInside];
            self.avatarBtn = btn;
            
            UILabel *label = [UILabel createLabelWithFrame:CGRectZero BackgroundColor:[UIColor colorWithColor:sl_blackColors alpha:0.6] Text:NSLocalizedString(@"默认", nil) Font:SLPFFont(__ScaleWidth(11)) TextColor:sl_whiteTextColors];
            label.textAlignment = NSTextAlignmentCenter;
            label.layer.masksToBounds = YES;
            label.layer.cornerRadius = 5;
            [btn addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(__ScaleWidth(9));
                make.width.mas_equalTo(__ScaleWidth(38));
                make.height.mas_equalTo(__ScaleWidth(18));
                make.top.mas_equalTo(__ScaleWidth(7));
            }];
            
        }else{
//            BXPhotoModel *model = self.photoAlbums[k-1];
            HPersonalPhotoModel *model = self.photoAlbums[k-1];
            if (model.url) {
                [btn yy_setImageWithURL:[NSURL URLWithString:model.url] forState:BtnNormal placeholder:CImage(@"placeholder_avatar_67")];
            }else{
                [btn setImage:model.image forState:BtnNormal];
            }
            btn.tag = k - 1;
            
            [btn addTarget:self action:@selector(changeAlbumPhoto:) forControlEvents:BtnTouchUpInside];
            
            UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn addSubview:deleteBtn];
            [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(0);
                make.top.mas_equalTo(0);
                make.width.height.mas_equalTo(__ScaleWidth(25));
            }];
            [deleteBtn setImage:CImage(@"setting_delete") forState:BtnNormal];
            
            [deleteBtn addTarget:self action:@selector(deleteBtnAction:) forControlEvents:BtnTouchUpInside];
            deleteBtn.tag = 20 + k - 1;
        }
        
    }
    
    if (allCount < 9) {
        UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        CGFloat x = __ScaleWidth(12 + (106+15)*(allCount%3));
        CGFloat y = __ScaleWidth(15) + __ScaleWidth((15+107)*(allCount/3));
        addBtn.frame = CGRectMake(x, y, __ScaleWidth(106), __ScaleWidth(107));
        [self.topView addSubview:addBtn];
        
        [addBtn setBackgroundImage:CImage(@"add_photo") forState:BtnNormal];
        
        [addBtn addTarget:self action:@selector(addPhoto) forControlEvents:BtnTouchUpInside];
    }
    
//    检测是否有需要更新的图片
    BOOL isNeed = NO;
    for (HPersonalPhotoModel *mmmd in self.photoAlbums) {
        if (mmmd.image && mmmd.url == nil) {
            isNeed = YES;
            break;
        }
    }
    
    _sureBtn.selected = isNeed;
    
    [self.mainTableView setTableHeaderView:self.topSuperView];
}

#pragma mark - 删除照片
-(void)deleteBtnAction:(UIButton *)btn{
    
    NSInteger deleteIndex = btn.tag - 20;
    [self.photoAlbums removeObjectAtIndex:deleteIndex];
    [self updateTopView];
    self.sureBtn.selected = YES;
}



#pragma mark - 替换照片墙的照片
-(void)changeAlbumPhoto:(UIButton *)btn{
    NSLog(@"aaaaa");
//    替换的第几张
    
    self.replaceIndex = btn.tag;
    
    self.photoType = @"2";
    [self.manager clearSelectedList];
    _manager.configuration.movableCropBox = NO;
    self.manager.configuration.photoMaxNum = 1;
    _manager.configuration.singleSelected = YES;
    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.manager delegate:self];
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - 新增照片
-(void)addPhoto{
    
//    重新配置manager
    self.photoType = @"1";
    [self.manager clearSelectedList];
    self.manager.configuration.photoMaxNum = 8 - self.photoAlbums.count;
    self.manager.configuration.singleSelected = NO;
    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.manager delegate:self];
    [self presentViewController:nav animated:YES completion:nil];
    
}

#pragma mark - 初始化导航栏
-(void)setupNavigationView{
    _navigationView = [UIView new];
    [self.view addSubview:_navigationView];
    [_navigationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(__kTopAddHeight+64);
    }];
    [_navigationView setBackgroundColor:[UIColor sl_colorWithHex:0xFFFFFF]];
    WS(weakSelf);
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn addTarget:self action:@selector(pop) forControlEvents:BtnTouchUpInside];
    [_navigationView addSubview:backBtn];
    [backBtn setImage:CImage(@"back_black") forState:BtnNormal];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.mas_equalTo(0);
        make.width.height.mas_equalTo(44);
    }];
    UILabel *label = [UILabel createLabelWithFrame:CGRectZero BackgroundColor:SLClearColor Text:NSLocalizedString(@"编辑资料", nil) Font:SLBFont(__ScaleWidth(18)) TextColor:sl_textColors];
    label.textAlignment = 1;
    [_navigationView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(44);
        make.right.mas_equalTo(-44);
        make.centerY.equalTo(weakSelf.navigationView.mas_bottom).offset(-22);
        make.height.mas_equalTo(25);
    }];
}


- (void)didGetBXLiveUser:(BXLiveUser *)liveUser {
    NSMutableArray *tempArray = [NSMutableArray array];
    
    NSMutableArray *section0 = [NSMutableArray array];
    NSMutableArray *section1 = [NSMutableArray array];
    NSMutableArray *section2 = [NSMutableArray array];
    
    NSString *nickname = liveUser.nickname;
    if (IsNilString(nickname)) {
        nickname = NSLocalizedString(@"未设置", nil);
    }
    [section0 addObject:nickname];
    
    [section0 addObject:liveUser.user_id];
    
    NSString *sex = NSLocalizedString(@"未设置", nil);
    if ([liveUser.gender integerValue] == 1) {
        sex = NSLocalizedString(@"男", nil);
    }else if ([liveUser.gender integerValue] == 2){
        sex = NSLocalizedString(@"女", nil);
    }
    [section0 addObject:sex];
    
    NSString *birthday = liveUser.birthday;
    if (IsNilString(birthday)) {
        birthday = NSLocalizedString(@"未设置", nil);
    }
    [section0 addObject:birthday];
    
    NSString *location = [NSString stringWithFormat:@"%@-%@-%@",liveUser.province_name,liveUser.city_name,liveUser.district_name];
    if(IsNilString(liveUser.province_name)&&IsNilString(liveUser.city_name)&&IsNilString(liveUser.district_name)) {
        location = NSLocalizedString(@"未设置", nil);
    }
    [section0 addObject:location];
    
//    身高
    
    NSString *height = [NSString stringWithFormat:@"%@",liveUser.height];
    
    [section0 addObject:height];
//    体重
    NSString *weight = [NSString stringWithFormat:@"%@",liveUser.weight];
    [section0 addObject:weight];
    
    [tempArray addObject:section0];
    
    NSString *sign = liveUser.sign;
    if (IsNilString(sign)) {
        sign = NSLocalizedString(@"修改签名", nil);
    }
    [section1 addObject:sign];
    if (liveUser.impression) {
        [section1 addObject:liveUser.impression];
    }else{
        [section1 addObject:NSLocalizedString(@"修改同类标签", nil)];
    }
    [section1 addObject:NSLocalizedString(@"修改语音标签", nil)];
    
    [tempArray addObject:section1];
    
    if (liveUser.photo_wall_image && liveUser.photo_wall_image.count > 0) {
        [section2 addObject:liveUser.photo_wall_image[0]];
    }else{
        [section2 addObject:liveUser.avatar];
    }
    [section2 addObject:liveUser.cover];
    
    [tempArray addObject:section2];
    
    _contents = tempArray;
    
    [_mainTableView reloadData];
    
}
#pragma mark - 创建表单视图
- (void)createTableView {

    _topSuperView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, __kWidth, __ScaleWidth(122 + 45))];
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, __kWidth, __ScaleWidth(122))];
    
    [_topSuperView addSubview:self.topView];
    _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_topSuperView addSubview:_sureBtn];
    [_sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(__ScaleWidth(-15));
        make.width.mas_equalTo(__ScaleWidth(52));
        make.height.mas_equalTo(__ScaleWidth(26));
        make.bottom.mas_equalTo(__ScaleWidth(-10));
    }];
    [_sureBtn setTitle:NSLocalizedString(@"保存", nil) forState:BtnNormal];
    [_sureBtn setTitleColor:sl_textSubColors forState:BtnNormal];
    [_sureBtn setTitleColor:sl_whiteTextColors forState:BtnSelected];
    [_sureBtn setBackgroundImage:[UIImage imageWithColor:sl_subBGColors] forState:BtnNormal];
    [_sureBtn setBackgroundImage:[UIImage imageWithColor:sl_normalColors] forState:BtnSelected];
    _sureBtn.titleLabel.font = SLPFFont(14);
    [_sureBtn bringSubviewToFront:_sureBtn.titleLabel];
    [_sureBtn.layer setMasksToBounds:YES];
    _sureBtn.layer.cornerRadius = __ScaleWidth(13);
    
    [_sureBtn addTarget:self action:@selector(sureBtnAction) forControlEvents:BtnTouchUpInside];
    
    _countLabel = [UILabel createLabelWithFrame:CGRectZero BackgroundColor:SLClearColor Text:NSLocalizedString(@"第一张默认为头像，共9张", nil) Font:SLPFFont(11) TextColor:sl_textSubColors];
    [_topSuperView addSubview:_countLabel];
    [_countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(__ScaleWidth(12));
        make.bottom.mas_equalTo(__ScaleWidth(-15));
        make.height.mas_equalTo(__ScaleWidth(16));
    }];
    
    
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    self.mainTableView.backgroundColor = [UIColor clearColor];
    self.mainTableView.showsVerticalScrollIndicator = YES;
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTableView.tableHeaderView = self.topSuperView;
    self.mainTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.mainTableView];
    WS(weakSelf);
    [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.equalTo(weakSelf.navigationView.mas_bottom);
    }];
}

#pragma mark - 上传并更新数据
-(void)sureBtnAction{
//    确定按钮点击
    if (!_sureBtn.selected) {
        
        [SLProgressHUD slShowInfoWithMessage:NSLocalizedString(@"您还未选择照片", nil)];
        
        return;
    }
    
//    找出需要上传的图片。
    NSMutableArray *needUploadArray = [NSMutableArray new];
    for (HPersonalPhotoModel *model in self.photoAlbums) {
        if (model.image) {
            [needUploadArray addObject:model];
        }
    }
     WS(weakSelf);
    if (needUploadArray.count == 0) {
//        仅仅删除了
        NSMutableArray *mutabStrs = [NSMutableArray new];
        for (int i=0; i<weakSelf.photoAlbums.count; i++) {
            HPersonalPhotoModel *m = weakSelf.photoAlbums[i];
            if (m.url) {
                [mutabStrs addObject:m.url];
            }
        }
        NSString *imageString = [mutabStrs componentsJoinedByString:@","];
        [[NewHttpManager sharedNetManager] POST:@"s=Useralbum.savaPhoto" parameters:@{@"image":imageString} success:^(id  _Nonnull responseObject) {
            NSLog(@"%@",responseObject);
            if ([responseObject[@"code"] integerValue] == 0) {
                BXLiveUser *liveUser = [BXLiveUser currentBXLiveUser];
                liveUser.photo_wall_image = [mutabStrs copy];
                [BXLiveUser setCurrentBXLiveUser:liveUser];
                weakSelf.sureBtn.selected = NO;
                [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"修改成功", nil)];
            }else{
                
            }
        } failure:^(NSError * _Nonnull error) {
            [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"修改失败", nil)];
        }];
        
        return;
    }
    
    //    上传
    [BGProgressHUD showProgress:1.0/needUploadArray.count status:[NSString stringWithFormat:NSLocalizedString(@"上传中 %@ / %lu", nil),@1,(unsigned long)needUploadArray.count]];
    
    for (int i=0;i<needUploadArray.count; i++) {
        
        HPersonalPhotoModel *model = needUploadArray[i];
        UIImage *croppedImage = model.image;
        NSData *data = UIImageJPEGRepresentation(croppedImage, .8);
        
        [SLUpLoadAndDownloadTools uploadFileWithType:@"album" fileName:[self getFileName] data:data success:^(NSDictionary *jsonDic, BOOL flag, NSMutableArray *models) {
                if (flag) {
                    weakSelf.updatePhotoSuccessCount = weakSelf.updatePhotoSuccessCount + 1;
                    [BGProgressHUD showProgress:((float)(weakSelf.updatePhotoFailCount+weakSelf.updatePhotoSuccessCount))/needUploadArray.count status:[NSString stringWithFormat:NSLocalizedString(@"上传中 %ld / %lu", nil),(long)weakSelf.updatePhotoSuccessCount,(unsigned long)needUploadArray.count]];
                    NSString *imgUrl = jsonDic[@"filePath"];
                    
//                    [weakSelf.photoAlbums replaceObjectAtIndex:lastIndex+i withObject:imgUrl];
                    model.url = imgUrl;
//                      上传后图片的url
                    if (weakSelf.updatePhotoFailCount + weakSelf.updatePhotoSuccessCount == needUploadArray.count) {
//                        已经上传完了。
                        [BGProgressHUD hidden];
                        weakSelf.updatePhotoSuccessCount = 0;
                        weakSelf.updatePhotoFailCount = 0;
                        NSMutableArray *mutabStrs = [NSMutableArray new];
                        for (int i=0; i<weakSelf.photoAlbums.count; i++) {
                            HPersonalPhotoModel *m = weakSelf.photoAlbums[i];
                            if (m.url) {
                                [mutabStrs addObject:m.url];
                            }
                        }
                        NSString *imageString = [mutabStrs componentsJoinedByString:@","];
                        [[NewHttpManager sharedNetManager] POST:@"s=Useralbum.savaPhoto" parameters:@{@"image":imageString} success:^(id  _Nonnull responseObject) {
                            NSLog(@"%@",responseObject);
                            if ([responseObject[@"code"] integerValue] == 0) {
                                BXLiveUser *liveUser = [BXLiveUser currentBXLiveUser];
                                liveUser.photo_wall_image = [mutabStrs copy];
                                [BXLiveUser setCurrentBXLiveUser:liveUser];
                                weakSelf.sureBtn.selected = NO;
                                [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"修改成功", nil)];
                            }else{
                                
                            }
                        } failure:^(NSError * _Nonnull error) {
                            [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"修改失败", nil)];
                        }];
                    }
                } else {
//                    [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"上传失败", nil)];
                    weakSelf.updatePhotoFailCount++;
                    
                    if (weakSelf.updatePhotoFailCount + weakSelf.updatePhotoSuccessCount == needUploadArray.count) {
//                        已经上传完了。但是有上传失败的。
                        [BGProgressHUD hidden];
                        weakSelf.updatePhotoSuccessCount = 0;
                        weakSelf.updatePhotoFailCount = 0;
                    }
                }
        } failure:^(NSError *error) {
            weakSelf.updatePhotoFailCount++;
            if (weakSelf.updatePhotoFailCount + weakSelf.updatePhotoSuccessCount == needUploadArray.count) {
    //                        已经上传完了。但是有上传失败的。
                [BGProgressHUD hidden];
            }
        }];
    }
}



#pragma mark - 更换头像
- (void)setHeadBtnClick {
    if (_type) {
        return;
    }
    self.photoType = @"0";
    [self.manager clearSelectedList];
    self.manager.configuration.singleSelected = YES;
    self.manager.configuration.singleJumpEdit = YES;
    _manager.configuration.movableCropBox = YES;
    self.manager.configuration.movableCropBoxCustomRatio = CGPointMake(500, 500);
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:NSLocalizedString(@"更换头像", nil) preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *paizhao = [UIAlertAction actionWithTitle:NSLocalizedString(@"拍照", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [self.view hx_showImageHUDText:NSLocalizedString(@"此设备不支持相机!", nil)];
            return;
        }
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"无法使用相机", nil) message:NSLocalizedString(@"请在设置-隐私-相机中允许访问相机", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"设置", nil), nil];
            [alert show];
            
#pragma clang diagnostic pop
            
            return;
        }
        [self hx_presentCustomCameraViewControllerWithManager:self.manager delegate:self];
    }];
    UIAlertAction *xiangce = [UIAlertAction actionWithTitle:NSLocalizedString(@"相册", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.manager delegate:self];
        [self presentViewController:nav animated:YES completion:nil];
        
    }];
    [alertVc addAction:cancle];
    [alertVc addAction:paizhao];
    [alertVc addAction:xiangce];
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark - 更换头部背景图
- (void)replaceBtnClick{
    if (_type) {
        return;
    }
    self.photoType = @"4";
    [self.manager clearSelectedList];
    self.manager.configuration.singleJumpEdit = YES;
    self.manager.configuration.singleSelected = YES;
    self.manager.configuration.movableCropBoxCustomRatio = CGPointMake(1000, 7.7*1000/16.f);
    [self hx_presentSelectPhotoControllerWithManager:self.manager delegate:self];
}

#pragma mark - UITableView delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titles.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sectionTitles = self.titles[section];
    return sectionTitles.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return __ScaleWidth(62);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 1) {
        BXPersonDataIdCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonDataIdCell"];
        if (!cell) {
            cell = [[BXPersonDataIdCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PersonDataIdCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        NSInteger type = 0;
        if (!_type) {
            type = 1;
        }
        [cell setTitle:_titles[indexPath.section][indexPath.row] subTitle:_contents[indexPath.section][indexPath.row] type:type];
        return cell;
    } else if(indexPath.section == 2) {
        BXPersonDataPicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BXPersonDataPicCell"];
        if (!cell) {
            cell = [[BXPersonDataPicCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BXPersonDataPicCell"];
        }
        [cell setTitle:_titles[indexPath.section][indexPath.row] subTitle:_contents[indexPath.section][indexPath.row]];
        return cell;
    } else {
        HHPersonDataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SettingCell"];
        if (!cell) {
            cell = [[HHPersonDataCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SettingCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell setTitle:_titles[indexPath.section][indexPath.row] subTitle:_contents[indexPath.section][indexPath.row] color:sl_textColors type:1 isLast:0];
        return cell;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, __kWidth, __ScaleWidth(10))];
    v.backgroundColor = sl_subBGColors;
    return v;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_type) {
        return;
    }
    WS(ws);
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) { //昵称
            HNickNameVC *hnnvc = [[HNickNameVC alloc]init];
            hnnvc.nickName = _contents[indexPath.section][indexPath.row];
            hnnvc.didUpdateNickName = ^(NSString *nickName) {
                [ws.contents[0] replaceObjectAtIndex:0 withObject:nickName];
                [ws.mainTableView reloadData];
            };
            [self.navigationController pushViewController:hnnvc animated:YES];
        } else if (indexPath.row == 1) { //复制
            
        }else if (indexPath.row == 2) { //性别
            [self createSexAlert];
        }else if (indexPath.row == 3) { //出生日期
            [self createBirthday];
        }else if (indexPath.row == 4) { //所在地
            if (!self.provinceArray.count) {
                [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"获取信息失败", nil)];
                return;
            }
            [self createAddressAlert];
        }else if (indexPath.row  == 5) { // 身高
            NSLog(NSLocalizedString(@"身高", nil));
            [self createHeightAlert];
            
        }else if (indexPath.row  == 6) { // 体重
            NSLog(NSLocalizedString(@"体重", nil));
            [self createWeightAlert];
        }
        
        
    }else if (indexPath.section == 1) {
        //个性签名
        if (indexPath.row == 0) {
            WS(ws);
            HPersonalizedSignatureVC *hpstvc = [[HPersonalizedSignatureVC alloc]init];
            hpstvc.sign = _contents[indexPath.section][indexPath.row];
            hpstvc.didUpdateSign = ^(NSString *sign) {
                [ws.contents[1] replaceObjectAtIndex:0 withObject:sign];
                [ws.mainTableView reloadRow:0 inSection:1 withRowAnimation:UITableViewRowAnimationNone];
            };
            [self.navigationController pushViewController:hpstvc animated:YES];
        }else if (indexPath.row == 1){
//            同类标签
            BXPersonDataTagTypeVC *vc = [[BXPersonDataTagTypeVC alloc]init];
            vc.complateBlock = ^(NSString * _Nonnull imp) {
//              保存成功
                [ws.contents[1] replaceObjectAtIndex:1 withObject:imp];
                [ws.mainTableView reloadRow:1 inSection:1 withRowAnimation:UITableViewRowAnimationNone];
            };
//
            vc.selArray = [NSMutableArray arrayWithArray:@[]];
            
            [self pushVc:vc];
        }else if (indexPath.row == 2){
//            语音标签
            BXPersonDataVoiceVC *vc = [[BXPersonDataVoiceVC alloc]init];
            [self pushVc:vc];
        }
    }else if (indexPath.section ==  2) {
        if(indexPath.row == 0) {
//            背景墙
            [self replaceBtnClick];
        }
    }
}
#pragma mark - 体重
-(void)createWeightAlert{
    SLSettingWeightView *swV = [[SLSettingWeightView alloc] initWithFrame:CGRectMake(0, 0, __kWidth, __kHeight)];
    [swV defaultRow:[NSString stringWithFormat:@"%@",[BXLiveUser currentBXLiveUser].weight]];
    WS(weakSelf);
    swV.weightComplateBlock = ^(NSString * _Nonnull weight) {
        [weakSelf.contents[0] replaceObjectAtIndex:6 withObject:weight];
        [weakSelf.mainTableView reloadData];
    };
    [swV show];
}
#pragma mark - 身高
-(void)createHeightAlert{
    SLSettingHeightView *swV = [[SLSettingHeightView alloc] initWithFrame:CGRectMake(0, 0, __kWidth, __kHeight)];
    [swV defaultRow:[NSString stringWithFormat:@"%@",[BXLiveUser currentBXLiveUser].height]];
    WS(weakSelf);
    swV.heightComplateBlock = ^(NSString * _Nonnull height) {
        [weakSelf.contents[0] replaceObjectAtIndex:5 withObject:height];
        [weakSelf.mainTableView reloadData];
    };
    [swV show];
}

//section底部间距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return __ScaleWidth(10);
}
//section底部视图
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
//    view.backgroundColor = [UIColor clearColor];
//    return view;
//}

#pragma mark - 选择性别弹框
- (void)createSexAlert{
    
    SLSettingGenderView *genderV = [[SLSettingGenderView alloc] initWithFrame:CGRectMake(0, 0, __kWidth, __kHeight)];
    WS(weakSelf);
    [genderV setComplateBlock:^(NSString * _Nonnull gender) {
        [[NewHttpRequestHuang sharedNewHttpRequestHuang] userSaveInfoWithNickName:@"" Gender:gender Birthday:@"" Province_id:@"" City_id:@"" District_id:@"" Sign:@"" Fields:@"gender" Success:^(id responseObject) {
            if ([responseObject[@"code"] intValue]==0) {
                
                BXLiveUser *liveUser = [BXLiveUser currentBXLiveUser];
                
                liveUser.gender = gender;
                
                [BXLiveUser setCurrentBXLiveUser:liveUser];
                
                if ([gender isEqualToString:@"1"]) {
                    [weakSelf.contents[0] replaceObjectAtIndex:2 withObject:NSLocalizedString(@"男", nil)];
                }else if ([gender isEqualToString:@"2"]) {
                    [weakSelf.contents[0] replaceObjectAtIndex:2 withObject:NSLocalizedString(@"女", nil)];
                }
                
                [weakSelf.mainTableView reloadData];

                
            }else {
                [BGProgressHUD showInfoWithMessage:responseObject[@"msg"]];
            }
        } Failure:^(NSError *error) {
            [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"修改失败", nil)];
        }];
    }];
    
    [genderV show];
}

#pragma mark - 出生日期选择器
-(void)createBirthday {
    
    SLSettingBirthdayView *bv = [[SLSettingBirthdayView alloc] initWithFrame:CGRectMake(0, 0, __kWidth, __kHeight)];
    WS(weakSelf);
    bv.birthdayComplateBlock = ^(NSString * _Nonnull birthday) {
        [weakSelf.contents[0] replaceObjectAtIndex:3 withObject:birthday];
        [weakSelf.mainTableView reloadData];
    };
    [bv show];
//
//
//    return;
//    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
//    datePickManager.style = PGDatePickManagerStyleSheet;
//    datePickManager.isShadeBackground = YES;
//    PGDatePicker *datePicker = datePickManager.datePicker;
//    datePicker.showUnit = PGShowUnitTypeNone;
//    //设置头部的背景颜色
//    datePickManager.headerViewBackgroundColor = RGB(246, 246, 246);
//    //设置线条的颜色
//    datePicker.lineBackgroundColor = normalColors;
//    //设置选中行的字体颜色
//    datePicker.textColorOfSelectedRow = normalColors;
//    //设置未选中行的字体颜色
//    datePicker.textColorOfOtherRow = UIColorHex(333333);
//    //设置取消按钮的字体颜色
//    datePickManager.cancelButtonTextColor = MinorColor;
//    //设置取消按钮的字
//    datePickManager.cancelButtonText = NSLocalizedString(@"取消", nil);
//    //设置取消按钮的字体大小
//    datePickManager.cancelButtonFont = [UIFont boldSystemFontOfSize:15];
//    //设置确定按钮的字体颜色
//    datePickManager.confirmButtonTextColor = normalColors;
//    //设置确定按钮的字
//    datePickManager.confirmButtonText = NSLocalizedString(@"确定", nil);
//    //设置确定按钮的字体大小
//    datePickManager.confirmButtonFont = [UIFont boldSystemFontOfSize:15];
//    datePicker.isHiddenMiddleText = false;
//    datePicker.delegate = self;
//    datePicker.datePickerType = PGDatePickerTypeVertical;
//    datePicker.datePickerMode = PGDatePickerModeDate;
//    datePicker.maximumDate = [NSDate date];
//    datePicker.minimumDate = [NSDate dateWithString:@"1919-01-01" format:@"yyyy-MM-dd"];
//    datePicker.datePickerType = PGDatePickerTypeLine;
//    [self presentViewController:datePickManager animated:NO completion:nil];
}

#pragma mark - 选择省市区弹框
- (void)createAddressAlert{
    self.pickerView = [UIPickerView new];
    self.pickerView.frame = CGRectMake(0, 40, SCREEN_WIDTH - 20, 200);
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.pickerView selectRow:self.seletedProvinceIndex inComponent:0 animated:YES];
    [self.pickerView selectRow:self.seletedCityIndex inComponent:1 animated:YES];
    [self.pickerView selectRow:self.seletedAreaIndex inComponent:2 animated:YES];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"选择城市\n\n\n\n\n\n\n\n\n\n\n", nil) message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *procinceStr = self.provinceArray[self.seletedProvinceIndex][@"provincename"];
        NSString *cityStr = self.provinceArray[self.seletedProvinceIndex][@"city"][self.seletedCityIndex][@"cityname"];
        NSString * areaStr = self.provinceArray[self.seletedProvinceIndex][@"city"][self.seletedCityIndex][@"area"][self.seletedAreaIndex][@"areaname"];
        
        NSString *cityID = self.provinceArray[self.seletedProvinceIndex][@"city"][self.seletedCityIndex][@"id"];
        NSString *provinceID = self.provinceArray[self.seletedProvinceIndex][@"id"];
        NSString *areaID = self.provinceArray[self.seletedProvinceIndex][@"city"][self.seletedCityIndex][@"area"][self.seletedAreaIndex][@"id"];
        [[NewHttpRequestHuang sharedNewHttpRequestHuang] userSaveInfoWithNickName:@"" Gender:@"" Birthday:@"" Province_id:provinceID City_id:cityID District_id:areaID Sign:@"" Fields:@"province_id,city_id,district_id" Success:^(id responseObject) {
            if ([responseObject[@"code"] intValue] == 0) {
                BXLiveUser *liveUser = [BXLiveUser currentBXLiveUser];
                liveUser.province_name = procinceStr;
                liveUser.city_name = cityStr;
                liveUser.district_name = areaStr;
                [BXLiveUser setCurrentBXLiveUser:liveUser];
                
                [self.contents[0] replaceObjectAtIndex:4 withObject:[NSString stringWithFormat:@"%@-%@-%@",procinceStr,cityStr,areaStr]];
                [self.mainTableView reloadData];
                
            } else {
                [BGProgressHUD showInfoWithMessage:responseObject[@"msg"]];
            }
        } Failure:^(NSError *error) {
             [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"修改失败", nil)];
        }];
    }];
    
    
    [alertController.view addSubview:self.pickerView];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - UIPickerView Delegate
//以下3个方法实现PickerView的数据初始化
//确定picker的轮子个数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}
//确定picker的每个轮子的item数
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {//省份个数
        return self.provinceArray.count;
    } else if(component ==1) {//市的个数
        return [self.provinceArray[self.seletedProvinceIndex][@"city"] count];
    } else{//区/县的个数
       
         return [self.provinceArray[self.seletedProvinceIndex][@"city"][self.seletedCityIndex][@"area"] count];
        
    }
}
//确定每个轮子的每一项显示什么内容
#pragma mark 实现协议UIPickerViewDelegate方法
-(NSString *)pickerView:(UIPickerView *)pickerView
            titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {//选择省份名
        return [self.provinceArray objectAtIndex:row][@"provincename"];
    } else if(component == 1){//选择市名
        return [self.provinceArray objectAtIndex:self.seletedProvinceIndex][@"city"][row][@"cityname"];
    } else{//选择区/县名
        return [[self.provinceArray objectAtIndex:self.seletedProvinceIndex][@"city"] objectAtIndex:self.seletedCityIndex][@"area"][row][@"areaname"];
    }
}
//监听轮子的移动
- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        
        self.seletedProvinceIndex = row;
        [self.pickerView reloadComponent:1];
        self.seletedCityIndex = 0;
        [self.pickerView selectRow:0 inComponent:1 animated:NO];
        
        [self.pickerView reloadComponent:2];
        self.seletedAreaIndex = 0;
        [self.pickerView selectRow:0 inComponent:2 animated:NO];
        
    }else if(component == 1) {
        self.seletedCityIndex = row;
        [self.pickerView reloadComponent:2];
        self.seletedAreaIndex = 0;
        [self.pickerView selectRow:0 inComponent:2 animated:NO];
    }else{
        self.seletedAreaIndex = row;
    }
}

//重写方法
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont systemFontOfSize:16]];
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

#pragma mark - 相机获取照片
- (void)customCameraViewController:(HXCustomCameraViewController *)viewController didDone:(HXPhotoModel *)model{
    WS(weakSelf);
    model.selectIndexStr = @"1";
    [@[model] hx_requestImageWithOriginal:YES completion:^(NSArray<UIImage *> * _Nullable imageArray, NSArray<HXPhotoModel *> * _Nullable errorArray) {
        [weakSelf loadImage:imageArray[0]];
    }];
}

#pragma mark - 相册获取到照片
-(void)photoNavigationViewController:(HXCustomNavigationController *)photoNavigationViewController didDoneAllList:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photoList videos:(NSArray<HXPhotoModel *> *)videoList original:(BOOL)original{
    NSLog(@"选择了照片");
    WS(weakSelf);
    
    [photoList hx_requestImageWithOriginal:original completion:^(NSArray<UIImage *> * _Nullable imageArray, NSArray<HXPhotoModel *> * _Nullable errorArray) {
        if ([weakSelf.photoType isEqualToString:@"0"]) {        //更换头像
            [weakSelf loadImage:imageArray[0]];
        }else if([weakSelf.photoType isEqualToString:@"1"]){    //新增照片
            [weakSelf loadImages:imageArray];
        }else if ([weakSelf.photoType isEqualToString:@"2"]) {    //更换照片
            [weakSelf changeSinglePhoto:imageArray[0]];
        }else if ([weakSelf.photoType isEqualToString:@"4"]) {    //更换照片
            [weakSelf changeBGPhoto:imageArray[0]];
        }
    }];
}
#pragma mark - 更换背景图
-(void)changeBGPhoto:(UIImage *)croppedImage{
    WS(weakSelf);
    NSData *data = UIImageJPEGRepresentation(croppedImage, .8);
    NSString *filePath = [self getImageFilePath:data];
    [SLUpLoadAndDownloadTools uploadFileWithType:@"cover" filePath:filePath success:^(NSDictionary *jsonDic, BOOL flag, NSMutableArray *models) {
        if (flag) {
            NSString *coverUrl = jsonDic[@"filePath"];
            [[NewHttpRequestHuang sharedNewHttpRequestHuang] UserSaveCoverWithCover:coverUrl Success:^(id responseObject) {
                if ([responseObject[@"code"]intValue]==0) {
                    
                    BXLiveUser *liveUser = [BXLiveUser currentBXLiveUser];
                    liveUser.cover = coverUrl;
                    [BXLiveUser setCurrentBXLiveUser:liveUser];
                    [weakSelf.contents[2] replaceObjectAtIndex:1 withObject:coverUrl];
                    [weakSelf.mainTableView reloadRow:1 inSection:2 withRowAnimation:UITableViewRowAnimationFade];
                    [SLProgressHUD slShowInfoWithMessage:NSLocalizedString(@"修改成功", nil)];
                } else {
                    [BGProgressHUD showInfoWithMessage:responseObject[@"msg"]];
                }
            } Failure:^(NSError *error) {
                [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"修改失败", nil)];
            }];
        } else {
            [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"上传失败", nil)];
        }
    } failure:^(NSError *error) {
        [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"上传失败", nil)];
    }];
}

-(void)changeSinglePhoto:(UIImage *)image{
    
    HPersonalPhotoModel *model = [[HPersonalPhotoModel alloc] init];
    model.url = nil;
    model.image = image;
    model.index = self.replaceIndex;
    
    [self.photoAlbums replaceObjectAtIndex:self.replaceIndex withObject:model];
    
    [self updateTopView];
    
    return;
}

-(void)loadImages:(NSArray <UIImage *>*)images{
    
    NSInteger currentIndex = self.photoAlbums.count;
    for ( int i=0; i<images.count;i++) {
        UIImage *image = images[i];
        HPersonalPhotoModel *model = [[HPersonalPhotoModel alloc] init];
        model.url = nil;
        model.image = image;
        model.index = currentIndex + i;
        [self.photoAlbums addObject:model];
    }
    
    [self updateTopView];
}


-(void)loadImage:(UIImage *)croppedImage{
    NSData *data = UIImageJPEGRepresentation(croppedImage, .8);
    NSString *filePath = [self getImageFilePath:data];
    [SLUpLoadAndDownloadTools uploadFileWithType:@"avatar" filePath:filePath success:^(NSDictionary *jsonDic, BOOL flag, NSMutableArray *models) {
        if (flag) {
            NSString *coverUrl = jsonDic[@"filePath"];
            [[NewHttpRequestHuang sharedNewHttpRequestHuang] UserSaveAvatarWithAvatar:coverUrl Success:^(id responseObject) {
                if ([responseObject[@"code"]intValue]==0) {
                    
                    BXLiveUser *liveUser = [BXLiveUser currentBXLiveUser];
                    liveUser.avatar = coverUrl;
                    [BXLiveUser setCurrentBXLiveUser:liveUser];
                    [self.avatarBtn yy_setImageWithURL:[NSURL URLWithString:coverUrl] forState:BtnNormal placeholder:CImage(@"placeholder_avatar_67")];
    
                    V2TIMUserFullInfo *info = [[V2TIMUserFullInfo alloc] init];
                    info.faceURL = liveUser.avatar;
                    
                    [[V2TIMManager sharedInstance] setSelfInfo:info succ:^{
                                            
                                        } fail:^(int code, NSString *desc) {
                                            
                                        }];
                    
//                    [[NIMSDK sharedSDK].userManager updateMyUserInfo:@{@(NIMUserInfoUpdateTagAvatar): liveUser.avatar} completion:^(NSError * _Nullable error) {
//
//                    }];
                } else {
                    [BGProgressHUD showInfoWithMessage:responseObject[@"msg"]];
                }
            } Failure:^(NSError *error) {
                [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"修改失败", nil)];
            }];
        } else {
            [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"上传失败", nil)];
        }
    } failure:^(NSError *error) {
        [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"上传失败", nil)];
    }];
}

-(NSString *)getFileName{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // 设置时间格式
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@%d.jpg",str,((arc4random() % 501) + 500)];
    return fileName;
}



-(NSString *)getImageFilePath:(NSData *)imageData {
    NSString *path = [[FilePathHelper getDocumentsPath] stringByAppendingPathComponent:@"avatar.jpg"];
    if([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    }
    [imageData writeToFile:path atomically:YES];
    return path;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma - mark PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    NSString *month = [NSString stringWithFormat:@"%ld",(long)dateComponents.month];
    if (month.length == 1) {
        month = [NSString stringWithFormat:@"0%@",month];
    }
    NSString *day = [NSString stringWithFormat:@"%ld",(long)dateComponents.day];
    if (day.length == 1) {
        day = [NSString stringWithFormat:@"0%@",day];
    }
    NSString *birthday = [NSString stringWithFormat:@"%ld-%@-%@",(long)dateComponents.year,month,day];
    
    [[NewHttpRequestHuang sharedNewHttpRequestHuang] userSaveInfoWithNickName:@"" Gender:@"" Birthday:birthday Province_id:@"" City_id:@"" District_id:@"" Sign:@"" Fields:@"birthday" Success:^(id responseObject) {
        if ([responseObject[@"code"] intValue]==0) {
            BXLiveUser *liveUser = [BXLiveUser currentBXLiveUser];
            liveUser.birthday = birthday;
            [BXLiveUser setCurrentBXLiveUser:liveUser];
            
            [self.contents replaceObjectAtIndex:3 withObject:liveUser.birthday];
            [self.mainTableView reloadData];
        }else{
            [BGProgressHUD showInfoWithMessage:responseObject[@"msg"]];
        }
    } Failure:^(NSError *error) {
        [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"修改失败", nil)];
    }];
}

@end

@implementation HPersonalPhotoModel

@end
